package com.boe.csb.core.common.csbsdk;

import com.alibaba.aosp.security.sdk.SignUtil;
import com.alibaba.csb.sdk.ContentBody;
import com.alibaba.csb.sdk.HttpCallerException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.security.InvalidParameterException;
import java.util.*;

/**
 * Created by tianxiang.luo on 17/1/13.
 */
public class HttpClientHelper {
    public HttpClientHelper() {
    }

    public static Map<String, String> newParamsMap(Map<String, String> paramsMap, String apiName, String version, String accessKey, String securityKey) {
        HashMap newParamsMap = new HashMap();
        HashMap headerParamsMap = new HashMap();
        if(paramsMap != null) {
            newParamsMap.putAll(paramsMap);
        }

        newParamsMap.put("_api_name", apiName);
        headerParamsMap.put("_api_name", apiName);
        if(version != null) {
            newParamsMap.put("_api_version", version);
            headerParamsMap.put("_api_version", version);
        }

        long ts = System.currentTimeMillis();
        newParamsMap.put("_api_timestamp", String.valueOf(ts));
        headerParamsMap.put("_api_timestamp", String.valueOf(ts));
        if(accessKey != null) {
            headerParamsMap.put("_api_access_key", accessKey);
            newParamsMap.put("_api_access_key", accessKey);
            newParamsMap.remove("_api_signature");
            headerParamsMap.put("_api_signature", SignUtil.sign(newParamsMap, securityKey));
        }

        return headerParamsMap;
    }

    public static String trimUrl(String requestURL) {
        int pos = requestURL.indexOf("?");
        String ret = requestURL;
        if(pos >= 0) {
            ret = requestURL.substring(0, pos);
        }

        return ret;
    }

    public static void validateParams(String apiName, String accessKey, String securityKey) throws HttpCallerException {
        if(apiName == null) {
            throw new HttpCallerException(new InvalidParameterException("param apiName can not be null!"));
        } else if(accessKey != null && securityKey == null) {
            throw new HttpCallerException(new InvalidParameterException("param securityKey can not be null for a given accessKey!"));
        }
    }

    public static Map<String, String> parseUrlParamsMap(String requestURL) throws HttpCallerException {
        boolean questionMarkFlag = requestURL.contains("?");
        HashMap urlParamsMap = new HashMap();
        if(questionMarkFlag) {
            int pos = requestURL.indexOf("?");
            String paramStr = requestURL.substring(pos + 1);
            String[] params = paramStr.split("&");
            String[] arr$ = params;
            int len$ = params.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                String param = arr$[i$];
                pos = param.indexOf("=");
                if(pos <= 0) {
                    throw new HttpCallerException("bad request URL, url params error:" + requestURL);
                }

                urlParamsMap.put(param.substring(0, pos), param.substring(pos + 1));
            }
        }

        return urlParamsMap;
    }

    public static StringEntity jsonProcess(Map<String, String> params) {
        JSONObject jsonParam = new JSONObject();
        Iterator entity = params.entrySet().iterator();

        while(entity.hasNext()) {
            Map.Entry entry = (Map.Entry)entity.next();
            jsonParam.put((String)entry.getKey(), entry.getValue());
        }

        StringEntity entity1 = new StringEntity(jsonParam.toString(), "UTF-8");
        entity1.setContentEncoding("UTF-8");
        entity1.setContentType("application/json");
        return entity1;
    }

    private static void setHeaders(HttpPost httpPost, Map<String, String> newParamsMap) {
        if(newParamsMap != null) {
            Iterator i$ = newParamsMap.entrySet().iterator();

            while(i$.hasNext()) {
                Map.Entry kv = (Map.Entry)i$.next();
                httpPost.addHeader((String)kv.getKey(), (String)kv.getValue());
            }
        }

    }

    public static void setHeaders(HttpGet httpGet, Map<String, String> newParamsMap) {
        if(newParamsMap != null) {
            Iterator i$ = newParamsMap.entrySet().iterator();

            while(i$.hasNext()) {
                Map.Entry kv = (Map.Entry)i$.next();
                httpGet.addHeader((String)kv.getKey(), (String)kv.getValue());
            }
        }

    }

    public static String genCurlHeaders(Map<String, String> newParamsMap) {
        if(newParamsMap == null) {
            return "";
        } else {
            StringBuffer sb = new StringBuffer();
            Iterator i$ = newParamsMap.entrySet().iterator();

            while(i$.hasNext()) {
                Map.Entry kv = (Map.Entry)i$.next();
                sb.append("-H \"").append((String)kv.getKey()).append(":").append((String)kv.getValue()).append("\"  ");
            }

            return sb.toString();
        }
    }

    public static String createPostCurlString(String url, Map<String, String> urlParams, Map<String, String> headerParams, ContentBody cb) {
        StringBuffer sb = new StringBuffer("curl ");
        sb.append(genCurlHeaders(headerParams));
        if(urlParams != null) {
            StringBuffer postSB = new StringBuffer();

            Map.Entry e;
            for(Iterator i$ = urlParams.entrySet().iterator(); i$.hasNext(); postSB.append((String)e.getKey()).append("=").append((String)e.getValue())) {
                e = (Map.Entry)i$.next();
                if(postSB.length() > 0) {
                    postSB.append("&");
                }
            }

            if(postSB.length() > 0) {
                sb.append(" -d \"");
                postSB.append("\"");
                sb.append(postSB.toString());
            }
        }

        sb.append(" --insecure ");
        sb.append(url);
        return sb.toString();
    }

    public static HttpPost createPost(String url, Map<String, String> urlParams, Map<String, String> headerParams, ContentBody cb) {
        HttpPost httpost = new HttpPost(url);
        setHeaders(httpost, headerParams);
        if(cb == null) {
            ArrayList be = new ArrayList();
            Set keySet = urlParams.keySet();
            Iterator e = keySet.iterator();

            while(e.hasNext()) {
                String key = (String)e.next();
                be.add(new BasicNameValuePair(key, (String)urlParams.get(key)));
            }

            try {
                httpost.setEntity(new UrlEncodedFormEntity(be, "UTF-8"));
            } catch (UnsupportedEncodingException var9) {
                var9.printStackTrace();
            }
        } else if(cb.getContentType() == ContentBody.Type.JSON) {
            StringEntity be1 = new StringEntity((String)cb.getContentBody(), "UTF-8");
            be1.setContentType(ContentBody.Type.JSON.getContentType());
            httpost.setEntity(be1);
        } else {
            httpost.setHeader("Content-Type", ContentBody.Type.BINARY.getContentType());
            ByteArrayEntity be2 = new ByteArrayEntity((byte[])((byte[])cb.getContentBody()));
            httpost.setEntity(be2);
        }

        return httpost;
    }
}
